
import mirny, MySQLdb # python-mysqldb
from mirny.plugins.input import Input

class MySQL(Input):
	name = _('MySQL Database')
	description = _('Sample plugin to get data from a MySQL database')
	params = {	'ip': (_('IP Address of the MySQL server'), str, True),
			'port': (_('Port of the MySQL server'), int, True),
			'user': (_('Username'), str, True),
			'passwd': (_('Password'), str, True),
			'db': (_('Database name'), str, True),
			'table': (_('Table to focus on'), str, False), 
			'charset': (_('Charset to use'), str, False), }
	config = {	'ip': '',
			'port': '3306',
			'user': 'root',
			'passwd': '',
			'db': 'mysql',
			'table': '',
			'charset': 'latin1', }
	def init_plugin(self):
		if len(self.config['ip']):
			self.db = MySQLdb.connect(host = self.config['ip'],
						  port = self.config['port'],
						  user = self.config['user'],
						  passwd=self.config['passwd'],
						  db   = self.config['db'] )
		else:
			self.db = MySQLdb.connect(user = self.config['user'],
						  passwd = self.config['passwd'],
						  db = self.config['db'])
		self.db.set_character_set(self.config['charset'])
		self.tables = self.db.cursor()
		self.tables.execute('show tables')
		return self.next()

	def next(self):
		self.table = self.tables.fetchone()
		if self.table is None:
			return False
		self.fetch = self.db.cursor()
		self.fetch.execute('select * from `'+self.table.replace('`','')+'`')
		
	def readline(self, size=10*1024*1024):
		return '\x00'.join(self.fetch.fetchone())[:size]

